const userService = require("../service/userService")
const controller = {
    async create(req, res) {
        const { username, password } = req.body
        const avatar = req.file ?
            "/uploads/" + req.file.filename :
            "/images/avatar.jpeg";
        await userService.create(username, password, avatar);
        res.send({ ok: 1 })
    },
    async find(req, res) {
        const { username, password } = req.body;
        let data = await userService.find(username, password)
        if (data.length) {
            // 如果验证通过了就设置一个session值
            req.session.user = data[0]
            res.send({ ok: 1, avatar: data[0].avatar })
        } else {
            res.send({ ok: 0 })
        }
    },
    async findAll(req, res) {
        let data = await userService.findAll()
        res.send(data)
    },
    async delete(req, res) {
        const { id, src } = req.query
        let data = await userService.delete(id)
        await userService.deleteFile(src)
        res.send({ ok: data.acknowledged })
    }
}

module.exports = controller